import React from 'react';
import cx from 'classnames';
import { routerRedux } from 'dva/router';
import { Flex, WingBlank, WhiteSpace, List, TextareaItem, Button } from 'antd-mobile';
import { createForm } from 'rc-form';
import styles from './styles.less';
import { SHEET_MAP } from 'const';

const questions = require('./questions.json');
const { Item, Item: { Brief } } = List;

function InquirySheet({ dispatch, location, detail, sheets, form, ...rest }) {

  const { pathname, query } = location;
  const { getFieldProps, getFieldValue, setFieldsValue, validateFields } = form;
  const options = [];
  Object.keys(detail).forEach(key => {
    if (/Q\d+$/i.test(key) && detail[key] ) {
      if (detail[key] != "undefined" && detail[key] != "") {
        options.push(...detail[key].split(';'));
      }
      
    }
  });
  
  function handleSubmit() {
    validateFields((err, values) => {
      
      Object.keys(values).forEach(key => {
        if(!values[key]){
            values[key] = "";
          }
        if (values[key] instanceof Array) {
          
          values[key] = values[key].join(';');
        }
      });
      values = { id: location.state.id, ...values, ...sheets };
      dispatch({
        type: 'inquiry/submit',
        payload: values,
      });
    });
  }

  function handleChange({ target: { type, name, value } }) {
    // 当 pathname == "/healthy/archives/inquiry/${用户的ID}/sheet"是不能点击选项的。
    if (type === 'radio') {// radio 单选
      setFieldsValue({ [name]: value });
    } else if (type === 'checkbox' && location.pathname =="/healthy/archives/inquiry/sheet") {// checkbox 多选
      const values = getFieldValue(name) || [];
      if (values.length === 0) {
        values.push(value);
        setFieldsValue({ [name]: values });
      } else {
        if (values.indexOf(value) !== -1) {
          values.splice(values.indexOf(value), 1);
        } else {
          for (var i in values) {
           if (values[i] == "没有" || values[i] == "正常") {
              let mutex = SHEET_MAP[values[i]+""+name];
              for (var j in mutex) {
                if(mutex[j] == value){
                  return false;
                }
              }
           }else{
              let mutex = SHEET_MAP[values[i]];
              for (let j in mutex){
                if(mutex[j] == value){
                  return false;
                }
              }
            }
          }
          values.push(value);

        }
        setFieldsValue({ [name]: values });
      }
    }
  }

  function isDisable(key, index, name) {
    const values = getFieldValue(key)|| [];
    for (var i in values) {
      // 问诊单选项有重复的,应该要互不影响。
      if (values[i] == "没有" || values[i] == "正常") {
        let mutex = SHEET_MAP[values[i]+""+key];
        for (var z in mutex) {
          if( mutex[z] == index){
            return true;
          }
        }
      }else{
        let mutex = SHEET_MAP[values[i]];
        for (var z in mutex) {
          if( mutex[z] == index){
            return true;
          }
        }
      }
    }
    return false;

  }

  function isActive(key, value) {
    if (detail[key] === value) {

      return true;
    }
    if (!getFieldValue(key)) {
      return false;
    }
    if (typeof(getFieldValue(key)) != "string") {
      const values = getFieldValue(key) || [];
      for (let i in values){
        if(values[i] === value){
          return true;
        }
      }
    }
    return getFieldValue(key) === value;
  }
  const Tonguephoto = () => {
    //舌照
    dispatch({
        type: 'wechat/chooseImage',
        payload: {
          sourceType: ['album'],
          actionType: 'inquiry/saveImage',
          field: 'tonguePic',
        },
      })
  }

  const Facephoto = () => {
    //面照
    dispatch({
        type: 'wechat/chooseImage',
        payload: {
          sourceType: ['album'],
          actionType: 'inquiry/saveImage',
          field: 'facePic',
        },
      })
  }

  const TongueCamera = () => {
    dispatch({
      type: 'wechat/chooseImage',
      payload: {
        sourceType: ['camera'],
        actionType: 'inquiry/saveImage',
        field: 'tonguePic',
      }
    })
  }

  const FaceCamera = () => {
    dispatch({
      type: 'wechat/chooseImage',
      payload: {
        sourceType: ['camera'],
        actionType: 'inquiry/saveImage',
        field: 'facePic',
      }
    })
  }

  const needSubmit = /inquiry\/sheet$/.test(pathname);

  return (
    <List>
      <TextareaItem
        {...getFieldProps('description',{
          initialValue: detail.description,
        }) }
        disabled={detail.description}
        placeholder="请填写病情"
        title="病情："
        clear
        autoFocus
        autoHeight />
      {questions.map((question, i) =>
        <Item key={i} >
          {`${i + 1}. ${question.label}`}
          <WhiteSpace />
          <Flex wrap="wrap" className={styles.questionOptions}>
            {question.options.map((value, j) => {
              const key = `q${i + 1}`;
              return (
                <label key={j} className={cx(styles.questionOption, styles.questionOptionNormal, { 
                  [styles.questionOptionActive]: isActive(key, value),
                  [styles.questionOptionDisable]: isDisable(key, value), })}>
                  {question.multiple ? (
                    <input
                      {...getFieldProps(key, {})}
                      type="checkbox"
                      name={key}
                      value={value}
                      checked={isActive(key, value)}
                      onChange={handleChange} />
                  ) : (
                    <input
                      {...getFieldProps(key)}
                      type="radio"
                      name={key}
                      value={value}
                      checked={isActive(key, value)}
                      disabled={detail[key]}
                      onChange={handleChange} />
                  )}
                  {value}
                </label>
              )
            })}
          </Flex>
        </Item>
      )}
      <Item extra={null}>
        <div style={{ height: '0.5rem'}}>
          <div style={{ float: 'left'}}>舌照：</div>
          <div style={{ float: 'right'}} onClick={TongueCamera}>拍照</div>
        </div>
         <Brief>
          {needSubmit ? (
            <Button
              type="button" 
              className={styles.addControl}
              onClick={Tonguephoto}
              >
              <span style={{display: 'inline-block',marginTop: '0.5rem'}}>+</span>
              </Button>
          ) : (
            <img src={rest.tonguePic} />
          )}
          {rest.tonguePic == "" ? "" : <img src={rest.tonguePic} />}
        </Brief>
      </Item>
      <Item extra={null}>
         <div style={{ height: '0.5rem'}}>
          <div style={{ float: 'left'}}>面照：</div>
          <div style={{ float: 'right'}} onClick={FaceCamera}>拍照</div>
        </div>
        <Brief>
          {needSubmit ? (
            <Button
              type="button" 
              className={styles.addControl}
              onClick={Facephoto}
              >
              <span style={{display: 'inline-block',marginTop: '0.5rem'}}>+</span>
              </Button>
          ) : (
            <img src={rest.facePic} />
          )}
          {rest.facePic == "" ? "" : <img src={rest.facePic} />}
        </Brief>
      </Item>
      {needSubmit && (query.s !== 'app') ? (
        <Item extra={null}>
          <WingBlank>
            <Button
              type="primary"
              onClick={handleSubmit}>提交</Button>
          </WingBlank>
          <WhiteSpace size="xl" />
        </Item>
      ) : null}
    </List>
  );
};

export default createForm()(InquirySheet);
